package org.fessingapore.library.daos.impl;


import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.fessingapore.library.daos.GenericDao;
import org.fessingapore.library.util.HibernateUtil;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;


public abstract class GenericDaoImpl<T, ID extends Serializable> implements GenericDao<T, ID> {
	private Class<T> persistentClass;
	private Session session;
	public GenericDaoImpl() {
		this.persistentClass = (Class<T>) ((ParameterizedType) getClass()
				.getGenericSuperclass()).getActualTypeArguments()[0];

	}

	public GenericDaoImpl(Class<T> type)  {
		persistentClass=type;
	}

	public void setSession(Session s) {
		this.session = s;
	}

	protected Session getSession() {
		if (session == null)
			session = HibernateUtil.getSessionFactory().openSession();
		return session;
	}

	public Class<T> getPersistentClass() {
		return persistentClass;
	}

	@SuppressWarnings("unchecked")
	public T getById(ID id) {
		T entity;
		entity = (T) getSession().load(getPersistentClass(), id);
		getSession().evict(entity);
		clear();
		return entity;
	}

	@SuppressWarnings("unchecked")
	public List<T> findAll() {
		System.out.println("findAll");
		Criteria crit = getSession().createCriteria(getPersistentClass());
		clear();
		return crit.list();

	}

	@SuppressWarnings("unchecked")
	public T create(T entity) {
		Transaction tx =null;
		try{

			tx = getSession().beginTransaction();
			getSession().save(entity);
			tx.commit();
			getSession().refresh(entity);
			getSession().evict(entity);
			clear();
		}catch (HibernateException e) {

			if(tx!=null) tx.rollback();
			entity=null;
			e.printStackTrace();
		}
		return entity;
	}

	@SuppressWarnings("unchecked")
	public boolean update(T entity) {
		Transaction tx =null;
		boolean status = false;
		try{
			tx = getSession().beginTransaction();
			getSession().merge(entity);
			tx.commit();
			clear();
			status=true;
		}catch (HibernateException e) {
			if(tx!=null) tx.rollback();
			e.printStackTrace();	
		}
		return status;
	}

	public boolean delete(T entity) {
		Transaction tx =null;
		boolean status = false;
		try{
			tx = getSession().beginTransaction();
			getSession().delete(entity);
			tx.commit();
			getSession().evict(entity);
			status=true;

		}catch (HibernateException e) {
			if(tx!=null) tx.rollback();
			e.printStackTrace();
		}
		return status;
	}

	public void flush() {
		getSession().flush();
	}

	public void clear() {
		getSession().clear();
	}

}
